package master

import (
	"context"
	"fmt"
	"github.com/kevinstudy2021/crontab-demo/common"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"time"
)

// mongodb日志管理
type LogMgr struct {
	client        *mongo.Client
	logCollection *mongo.Collection
}

var (
	G_logMgr *LogMgr
)

func InitLogMgr() (err error) {
	var (
		client *mongo.Client
	)

	client, err = connectMongoDB(G_config.MongodbUri, 5000*time.Millisecond)
	if err != nil {
		log.Fatal("Failed to connect to MongoDB:", err)
	}

	//clientOptions := options.Client().ApplyURI("mongodb://101.43.132.73:27017")
	//ctx, cancelFunc := context.WithTimeout(context.TODO(), timeout)
	//defer cancelFunc()
	// 建立mongodb连接
	//if client, err = mongo.Connect(
	//	ctx,
	//	clientOptions); err != nil {
	//	//G_config.MongodbUri,
	//	//clientopt.ConnectTimeout(time.Duration(G_config.MongodbConnectTimeout) * time.Millisecond)); err != nil {
	//	common.Logger.Error("Connect MongoDB Failed")
	//	return
	//}

	// 检查连接是否建立
	//if err = client.Ping(ctx, nil); err != nil {
	//	common.Logger.Error("Test Connect MongoDB Failed")
	//	return err
	//}

	G_logMgr = &LogMgr{
		client:        client,
		logCollection: client.Database("cron").Collection("log"),
	}
	return
}

// connectMongoDB 初始化 MongoDB 连接
func connectMongoDB(uri string, timeout time.Duration) (*mongo.Client, error) {
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
	if err != nil {
		return nil, err
	}

	// 检查连接是否建立
	err = client.Ping(ctx, nil)
	if err != nil {
		return nil, err
	}

	return client, nil
}

// 查看任务日志
func (logMgr *LogMgr) ListLog(name string, skip int64, limit int) (logArr []*common.JobLog, err error) {
	var (
		filter  *common.JobLogFilter
		logSort *common.SortLogByStartTime
		cursor  *mongo.Cursor
		jobLog  *common.JobLog
	)

	// len(logArr)
	logArr = make([]*common.JobLog, 0)

	// 过滤条件
	filter = &common.JobLogFilter{JobName: name}

	// 按照任务开始时间倒排
	logSort = &common.SortLogByStartTime{SortOrder: -1}

	// 查询
	if cursor, err = logMgr.logCollection.Find(context.TODO(), filter, &options.FindOptions{
		Sort: logSort,
		Skip: &skip,
	}); err != nil {
		common.Logger.Error(fmt.Sprintf("从mongoDB查询数据失败%v", err.Error()))
		return
	}

	//if cursor, err = logMgr.logCollection.Find(context.TODO(), filter, findopt.Sort(logSort), findopt.Skip(int64(skip)), findopt.Limit(int64(limit))); err != nil {
	//	return
	//}
	// 延迟释放游标
	defer cursor.Close(context.TODO())

	for cursor.Next(context.TODO()) {
		jobLog = &common.JobLog{}

		// 反序列化BSON
		if err = cursor.Decode(jobLog); err != nil {
			continue // 有日志不合法
		}

		logArr = append(logArr, jobLog)
	}
	return
}
